package com.zhou.message.dao;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.zhou.util.FileUtil;
import lombok.Data;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.sql.Blob;
import java.util.Date;

/**
 * <p>
 * 
 * </p>
 *
 * @author lang.zhou
 * @since 2023-03-01
 */
@Data
@TableName("sys_attachment")
public class Attachment implements Serializable {

    private static final long serialVersionUID=1L;

    /**
     * 系统附件表
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 用户id
     */
    private Integer userId;

    /**
     * 文件名
     */
    private String fileName;

    /**
     * 二进制
     */
    private InputStream file;

    /**
     * 文件后缀
     */
    private String prefix;

    /**
     * 文件类型；1-头像；2-文件
     */
    private Integer type;

    private String description;

    private Long size;

    @TableField(exist = false)
    private String fileSize;

    /**
     * 来源id
     */
    private Integer sourceId;

    /**
     * 附件来源
     */
    private String source;

    private Date createDt;

    private Integer isPub = 0;

    private String md5;

    private Date updateDt;

    public void setFile(Object file){
        try{
            if(file instanceof Blob){
                Blob blob = (Blob) file;
                this.file = blob.getBinaryStream();
            }else if(file instanceof byte[]){

                this.file = new ByteArrayInputStream((byte[]) file);
            }else if(file instanceof File){
                this.file = fileToInputStream((File) file);
            }else if(file instanceof String){
                this.file = fileToInputStream(new File((String) file));
            }else if(file instanceof InputStream){
                this.file = (InputStream) file;
            }else{
                throw new RuntimeException("获取文件字节流失败，无法识别对象类型！");
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void setSize(Long size) {
        this.fileSize = FileUtil.sizeToChinese(size);
        this.size = size;
    }

    private InputStream fileToInputStream(File file) throws IOException {
        FileInputStream in = null;
        try{
            return new ByteArrayInputStream(IOUtils.toByteArray((in = new FileInputStream(file))));
        }finally {
            IOUtils.closeQuietly(in);
        }
    }
}
